package com.example.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.Constants;
import com.example.common.core.domain.R;
import com.example.common.core.enums.ResultCode;
import com.example.common.core.utils.ThreadLocalUtil;
import com.example.common.security.exception.ServiceException;
import com.example.user.domain.course.Course;
import com.example.user.domain.course.dto.CourseQueryDTO;
import com.example.user.domain.course.vo.CourseDetailVO;
import com.example.user.domain.course.vo.CourseVO;
import com.example.user.domain.student.Student;
import com.example.user.domain.studentBuyCourse.StudentBuyCourse;
import com.example.user.domain.studentBuyCourse.dto.BuyCourseSaveDTO;
import com.example.user.mapper.StudentBuyCourseMapper;
import com.example.user.mapper.StudentMapper;
import com.example.user.mapper.course.CourseMapper;
import com.example.user.service.ICourseService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class CourseServiceImpl implements ICourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private StudentBuyCourseMapper studentBuyCourseMapper;


    @Override
    public List<CourseVO> list(CourseQueryDTO courseQueryDTO) {
        PageHelper.startPage(courseQueryDTO.getPageNum(), courseQueryDTO.getPageSize());
        courseQueryDTO.setTeacherId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        List<CourseVO> courseVOS = courseMapper.selectCourseList(courseQueryDTO);
        return courseVOS;
    }

    @Override
    public CourseDetailVO detail(Long courseId) {
        // 判断资源是否存在
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        CourseDetailVO courseDetailVO = new CourseDetailVO();
        BeanUtil.copyProperties(course, courseDetailVO);
        return courseDetailVO;
    }

    @Override
    public List<CourseVO> courseListForSale(CourseQueryDTO courseQueryDTO) {
        PageHelper.startPage(courseQueryDTO.getPageNum(), courseQueryDTO.getPageSize());
//        courseQueryDTO.setTeacherId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        // 设置只查询已发布状态的课程
        courseQueryDTO.setStatus(Course.STATUS_PUBLISHED);
        List<CourseVO> courseVOS = courseMapper.selectCourseList(courseQueryDTO);
        return courseVOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int buyCourse(BuyCourseSaveDTO buyCourseSaveDTO) {
        Long studentId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Course course = courseMapper.selectById(buyCourseSaveDTO.getCourseId());
        if (course == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        List<StudentBuyCourse> studentBuyCourses = studentBuyCourseMapper.selectList(new LambdaQueryWrapper<StudentBuyCourse>()
                .eq(StudentBuyCourse::getCourseId, buyCourseSaveDTO.getCourseId())
                .eq(StudentBuyCourse::getStudentId, studentId));
        if (CollectionUtil.isNotEmpty(studentBuyCourses)) {
            throw new ServiceException(ResultCode.FAILED_REPEAT_PURCHASE);
        }

        StudentBuyCourse studentBuyCourse = new StudentBuyCourse();
        studentBuyCourse.setCourseId(buyCourseSaveDTO.getCourseId());
        studentBuyCourse.setStudentId(studentId);
        return studentBuyCourseMapper.insert(studentBuyCourse);
    }

    @Override
    public List<CourseVO> purchasedCourseList(CourseQueryDTO courseQueryDTO) {
        PageHelper.startPage(courseQueryDTO.getPageNum(), courseQueryDTO.getPageSize());
        courseQueryDTO.setStudentId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        List<CourseVO> courseVOS = courseMapper.purchasedCourseList(courseQueryDTO);
        return courseVOS;
    }

    @Override
    public Boolean haveYouPurchased(Long courseId) {
        Long studentId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        Student student = studentMapper.selectById(studentId);
        if(student == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }else {
            if(student.getClassroomId()!=null && course.getClassroomId()!=null && student.getClassroomId().equals(course.getClassroomId())){
                return true;
            }
        }
        List<StudentBuyCourse> studentBuyCourses = studentBuyCourseMapper.selectList(new LambdaQueryWrapper<StudentBuyCourse>()
                .eq(StudentBuyCourse::getCourseId, courseId)
                .eq(StudentBuyCourse::getStudentId, studentId));
        if (CollectionUtil.isNotEmpty(studentBuyCourses)) {
            return true;
        }else{
            return false;
        }
    }

    @Override
    public List<CourseVO> classroomCourseList(CourseQueryDTO courseQueryDTO) {
        PageHelper.startPage(courseQueryDTO.getPageNum(), courseQueryDTO.getPageSize());
        List<CourseVO> courseVOS = courseMapper.selectCourseList(courseQueryDTO);
        return courseVOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> submitForReview(Long courseId) {
        // 获取当前用户ID（教师ID）
        Long teacherId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        
        // 查询课程
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        }
        
        // 验证是否为课程所有者
        if (!course.getTeacherId().equals(teacherId)) {
            return R.fail(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        // 验证课程是否有视频
        if (course.getVideoNum() == null || course.getVideoNum() <= 0) {

            return R.fail(ResultCode.THE_NUMBER_OF_VIDEOS_IS_ZERO);
        }
        
        // 验证当前状态是否为已创建或录制中或驳回
        if (course.getStatus() != Course.STATUS_CREATED 
            && course.getStatus() != Course.STATUS_RECORDING
            && course.getStatus() != Course.STATUS_REJECTED) {
            return R.fail(ResultCode.FAILED);
        }
        
        // 更新状态为待审核
        course.setStatus(Course.STATUS_REVIEWING);
        courseMapper.updateById(course);
        
        return R.ok("课程已提交审核");
    }
}
